package com.hotelManagerSystem.controller;

import com.hotelManagerSystem.model.Role;
import com.hotelManagerSystem.service.IRoleService;
import com.hotelManagerSystem.shiro.ShiroUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author treasy
 * @description 用户酒店后台人员登录和登出
 */

@Controller
@RequestMapping("/admin")
public class AdminLoginController {
    @Autowired
    private IRoleService iRoleService;

    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(Model model,String username,String password){
        Map<String, Object> map =new HashMap<>();
        //1.封装登录用户数据
        //realm认证会调用该token
        UsernamePasswordToken token = new ShiroUsernamePasswordToken(username,password,"Admin");
        //2.获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //3.执行登录方法
        try {
            subject.login(token);
            //登陆成功返回主界面
            map.put("code",200);
            map.put("message","登陆成功");
            Session session = subject.getSession();
            session.setAttribute("username",username);
            List<Role> roles = iRoleService.queryRoleListByUsername(username);
            String rolestr = roles.toString();
            session.setAttribute("roles",rolestr);
            System.out.println(rolestr);
        }catch (UnknownAccountException e){
            map.put("code",300);
            map.put("message","用户名不存在");
        }catch (IncorrectCredentialsException e){
            map.put("code",300);
            map.put("message","密码错误");
        }
        return map;
    }
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/admin/admin-login";
    }
}
